package hcQuest;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.Properties;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import webExperiment.ParticipantPanel;

public class HCQ extends JPanel {
    // -------------------------------------------------------------------------------
    // -------------------------------------------------------------------------------
    // EVENT HANDLING
    // -------------------------------------------------------------------------------
    // -------------------------------------------------------------------------------
    // -------------------------------------------------------------------------------
    // -------------------------------------------------------------------------------
    class Event implements ActionListener {
	final static int BTN_INSTRUCT = 2;
	final static int BTN_OK_PARTICIPANT = 3;
	final static int BTN_QUESTION = 8;
	final static int BTN_OK_HANDPANEL = 9;

	HCQ hdl;
	int id;

	public Event(HCQ theHdl, int theId) {
	    hdl = theHdl;
	    id = theId;
	}

	public void actionPerformed(ActionEvent e) {
	    switch (id) {
	    case BTN_INSTRUCT: // btn new part
		switch (InstructionScreen) {
		case 1:
		    instrPanel.setVisible(false);
		    fingerSeqPanel.setInstruction(l.handInstruction);
		    fingerSeqPanel.setVisible(true);
		    break;
		case 99:
		    HCQInterface.quitApplication();
		}// switch
		break;
	    case BTN_OK_PARTICIPANT:
		if (!partPanel.isObligatoryFilledIn()) {
		    break;
		}
		partPanel.setVisible(false);
		repaint();
		try {
		    sql.newParticipant();
		    if (sql.getSQLID() != HCQ_Database.ERROR) {
			sql.saveHCQPersonData(l.theLanguage, partPanel
				.getInitials(), partPanel.getGender(),
				partPanel.getYearOfBirth(), partPanel
					.getMTongue(), partPanel
					.getCountryOfBirth());
			showInstruction(l.countInstruction, 1, new Font(
				"Arial", Font.BOLD, 26));
		    } else {
		    }
		} catch (SQLException e1) {
		    // TODO Auto-generated catch block
		    e1.printStackTrace();
		}

		break;
	    case BTN_QUESTION:
		questPanel.setVisible(false);
		answers = answers + questPanel.getAnswers() + DATADELIM;
		if (!showNextQuestions()) {
		    saveDataAndQuit();
		}
		break;
	    case BTN_OK_HANDPANEL:
		fingerSeqPanel.setVisible(false);
		showNextQuestions();
		break;
	    } // end switch
	} // actionPerformed
    }// event class

    // -------------------------------------------------------------------------------
    /**
     * VERSION 1.1
     */
    private static final long serialVersionUID = 1L;
    public static final String VERSION = "HCQ1.1";
    private static final String INCPATH = "setting_files/";
    private static final String HANDPICT = "hands.gif";
    private static final String SQFTABLEFILE = "HCQ_data.sql";

    private static final String LOCALLANGFILE = "english";
    private static final String BTNTEXT = " OK ";

    private static final String DATADELIM = ",";
    private static final short NUMBERQUESTIONSCREENS = 2;
    private static final Color BGCOLOR = Color.white;

    private static final String INIFILE = "hcq.ini";
    private HCQ_Database sql;
    public Labels l = new Labels();
    private JPanel instrPanel = new JPanel();
    private JTextArea instrText = new JTextArea();
    private JScrollPane instrPane = new JScrollPane(instrText);
    private ParticipantPanel partPanel;
    private FingerSequencePanel fingerSeqPanel;
    private HCQ_QuestionPanel questPanel = new HCQ_QuestionPanel(BTNTEXT,
	    DATADELIM);
    // private int participantID;
    private String answers = "";
    private int InstructionScreen = 0;

    private int QuestionScreen = 0;
    JComboBox cbNationality = new JComboBox();
    JButton btnStartExp = new JButton();
    JButton instButton = new JButton();
    JButton btnVpCode = new JButton();
    private String experimentName;

    private HCQ_Interface HCQInterface;

    public HCQ(boolean isLocalApplication, HCQ_Interface theHCQInterface,
	    Class superClass, String lang, String theExperimentName,
	    boolean askSubjectID) {

	HCQInterface = theHCQInterface;
	experimentName = theExperimentName;

	setSize(800, 600);
	setLayout(null);
	setBackground(BGCOLOR);
	setVisible(true);

	// handPanel
	URL handPictURL = superClass.getResource(INCPATH + HANDPICT);
	if (handPictURL != null) {
	    fingerSeqPanel = new FingerSequencePanel(handPictURL, BTNTEXT,
		    BGCOLOR, DATADELIM);
	} else {
	    JOptionPane.showMessageDialog(this,
		    "ERROR: Picture File not found! ( " + INCPATH + HANDPICT
			    + " )");

	}
	fingerSeqPanel.setVisible(false);
	fingerSeqPanel.okButton.addActionListener(new Event(this,
		Event.BTN_OK_HANDPANEL));
	fingerSeqPanel.setLocation(
		(getWidth() - fingerSeqPanel.getWidth()) / 2, Math
			.round((getHeight() - fingerSeqPanel.getHeight()) / 2));
	fingerSeqPanel.setBackground(BGCOLOR);
	add(fingerSeqPanel);

	// part panel
	ParticipantPanel.askInitials = askSubjectID;
	ParticipantPanel.askResidence = false;
	ParticipantPanel.askCityOfBirth = false;
	partPanel = new ParticipantPanel(BTNTEXT);
	partPanel.okButton.addActionListener(new Event(this,
		Event.BTN_OK_PARTICIPANT));
	partPanel.setLocation((getWidth() - partPanel.getWidth()) / 2, Math
		.round((getHeight() - partPanel.getHeight()) / 2));
	partPanel.setBackground(BGCOLOR);

	add(partPanel);

	// question
	questPanel.setVisible(false);
	questPanel.okButton.addActionListener(new Event(this,
		Event.BTN_QUESTION));
	questPanel.setLocation((getWidth() - questPanel.getWidth()) / 2,
		(getHeight() - questPanel.getHeight()) / 2);
	add(questPanel);

	// Instruction PANEL
	instrPanel.setVisible(false);
	instrPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 100, 10));
	instrPanel.setSize(500, 350);
	instrPanel.setLocation((getWidth() - 500) / 2, (getHeight() - 350) / 2);
	instrPanel.setBackground(BGCOLOR);

	instButton.setText(BTNTEXT);
	instButton.addActionListener(new Event(this, Event.BTN_INSTRUCT));
	instButton.setSize(200, 30);

	instrPanel.add(instrPane);
	instrPanel.add(instButton);

	add(instrPanel);

	short DBMode;
	if (isLocalApplication) {
	    DBMode = HCQ_Database.FILE_MODE;
	} else {
	    DBMode = HCQ_Database.PHP_MODE;
	}

	/*
	 * if HCQ inifile exisit then reading inifile SQL, ask ini file?
	 */
	String sqldb = "false";
	URL ini = superClass.getResource(INCPATH + INIFILE);
	if (ini != null) {
	    Properties p = new Properties();
	    InputStream in;
	    try {
		in = ini.openStream();
		p.load(in);
		// SQL properties
		sqldb = p.getProperty("direct_SQL_connection").trim();
		// PHPPath
		String homeURL = p.getProperty("homeURL").trim();
		HCQ_Database.PHPPATH = homeURL + "/php_sql/";
		in.close();
	    } catch (IOException e) {
		e.printStackTrace();
	    }
	    if (sqldb.equals("true")) {
		DBMode = HCQ_Database.SQL_MODE;
	    }
	} else {
	    // using local file mode
	}

	URL SQLFile = superClass.getResource(INCPATH + SQFTABLEFILE);
	sql = new HCQ_Database(DBMode, experimentName, VERSION, ini, SQLFile);

	// Set Language
	// look for a local file (out side JAR)
	File localLangFile = new File(LOCALLANGFILE + ".xml");
	if (isLocalApplication && localLangFile.exists()) {
	    try {
		URL url = localLangFile.toURI().toURL();
		;
		l.readXMLFile(url);
	    } catch (MalformedURLException e) {
		e.printStackTrace();
	    }
	} else {
	    // if not take the specified inside JAR
	    if (lang == null) {
		lang = LOCALLANGFILE;
	    }
	    URL xmlURL = superClass.getResource(INCPATH + lang + ".xml");
	    if (xmlURL != null) {
		l.readXMLFile(xmlURL);
	    } else {
		JOptionPane.showMessageDialog(this, "ERROR: File not found! ("
			+ INCPATH + lang + ".xml )");
	    }

	}

	// Start
	if (l.xml.tagWasNotFound) {
	    showInstruction("Error reading language file: " + lang, 99);
	} else {
	    partPanel.writeLabels(l.lb);
	    partPanel.setVisible(true);
	    repaint();
	}
    }

    // -------------------------------------------------------------------------------

    @Override
    public void paint(Graphics g) {
	super.paint(g);
    }

    private void saveDataAndQuit() {
	// String sqlRtn =
	try {
	    sql.saveHCQData(fingerSeqPanel.getFingerSequenceString(),
		    fingerSeqPanel.getTimesString(), answers);
	    sql.writeEndTime();
	} catch (SQLException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
	HCQInterface.quitApplication();
    }

    private void showInstruction(String text, int InstructionCode) {
	showInstruction(text, InstructionCode,
		new Font("Arial", Font.PLAIN, 16));
    }

    private void showInstruction(String text, int InstructionCode, Font theFont) {
	// instrPanel.setBackground(Color.white);
	InstructionScreen = InstructionCode;
	instrText.setEditable(false);
	instrText.setLineWrap(true);
	instrText.setWrapStyleWord(true);
	instrText.setFont(theFont);
	instrText.setBackground(getBackground());
	instrText.setText(text);
	instrPane.setBorder(null);
	instrPane.setPreferredSize(new Dimension(400, 300));
	instrPanel.setVisible(true);
	repaint();
    }

    private boolean showNextQuestions() {
	boolean exist = true;

	QuestionScreen = QuestionScreen + 1;
	switch (QuestionScreen) {
	case 1:
	    questPanel.addHandQuestions(8);
	    questPanel.setQuestionText(1, l.Q[1], l.left, l.right, l.either);
	    questPanel.setQuestionText(2, l.Q[2], l.left, l.right, l.either);
	    questPanel.setQuestionText(3, l.Q[3], l.left, l.right, l.either);
	    questPanel.setQuestionText(4, l.Q[4], l.left, l.right, l.either);
	    questPanel.setQuestionText(5, l.Q[5], l.left, l.right, l.either);
	    questPanel.setQuestionText(6, l.Q[6], l.left, l.right, l.either);
	    questPanel.setQuestionText(7, l.Q[7], l.left, l.right, l.either);
	    questPanel.setQuestionText(8, l.Q[8], l.left, l.right, l.either);
	    break;
	case 2:
	    questPanel.addHandQuestions(5);
	    questPanel.setQuestionText(1, l.Q[9], l.left, l.right, l.either);
	    questPanel.setQuestionText(2, l.Q[10], l.left, l.right, l.either);
	    questPanel.setQuestionText(3, l.Q[11], l.left, l.right, l.either);
	    questPanel.setQuestionText(4, l.Q[12], l.left, l.right, l.either);
	    questPanel.setQuestionText(5, l.Q[13], l.left, l.right, l.either);
	    break;
	default:
	    exist = false;
	    break;
	}
	questPanel.setInfoText("(" + QuestionScreen + "/"
		+ NUMBERQUESTIONSCREENS + ")");
	if (exist) {
	    questPanel.setVisible(true);
	}
	repaint();
	return exist;
    }

} // main class

